package com.dtease.agent.core.mybatis.datasource;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
* @description 资源数据源配置
* @author chentl
* @class ResourceDataSourceConfig
* @package com.dtease.agent.metadata.config
* @since 2025/5/7 15:42
*/
@Configuration
@MapperScan(basePackages = "com.dtease.agent.biz.resource.mapper", sqlSessionFactoryRef = "resourceSqlSessionFactory")
public class ResourceDataSourceConfig {

    @Bean(name = "resourceDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.resource")
    public DataSource resourceDataSource() {
        return DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .build();
    }

    @Bean("resourceSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(
            @Qualifier("resourceDataSource") DataSource dataSource,
            MybatisPlusInterceptor mybatisPlusInterceptor
    ) throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setPlugins(mybatisPlusInterceptor);
        return sessionFactory.getObject();
    }

    @Bean("resourceTransactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("resourceDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
